<template>
  <table-row-detail-dialog ref="detailDialog" dialog-width="500" @confirm="addMenus">
    <div class="dialog-body">
      <div style="margin-bottom: 20px;">批量创建菜单，仅能创建顶级菜单和已存在的菜单的子菜单，多级菜单新建，需多次操作</div>
      <el-table :data="noAuthMenu">
        <el-table-column prop="authorityName" label="菜单名称"></el-table-column>
        <el-table-column prop="menuUrl" label="URL"></el-table-column>
        <el-table-column prop="parentId" label="上级菜单"></el-table-column>
      </el-table>
    </div>
  </table-row-detail-dialog>
</template>
<script>

import TableRowDetailDialog from '@/components/TableRowDetailDialog/index'
import {asyncRoutes} from '@/router'
import {list, batchCreate} from "@/api/system/authority";

let menuIndexObj = {};

let res = [];

function menuFilter(routes, parentPath = '') {
  routes.forEach(route => {
    const tmp = {...route};
    let fullPath = parentPath + tmp.path;
    tmp.parentPath = parentPath;
    if(menuIndexObj.hasOwnProperty(fullPath) || menuIndexObj.hasOwnProperty(tmp.redirect)) {
      if(tmp.children) {
        tmp.children = menuFilter(tmp.children, fullPath + '/')
      }
    }else {
      let parentId = parentPath ?
        menuIndexObj[parentPath.substring(0, parentPath.length - 1)].authorityId : '';

      res.push({
        authorityName: tmp.meta.title,
        enabled: 1,
        type: 1,
        parentId: parentId,
        menuUrl: fullPath
      })
    }
  });
}

export default {
  name: "ItemDetail",
  components: {
    TableRowDetailDialog,
  },
  props: {},
  data() {
    return {
      menuList: [],
      noAuthMenu: []
    }
  },
  computed: {},
  created() {
  },
  methods: {
    show() {
      this.$refs.detailDialog.show('edit');
      this.getList();
    },

    addMenus() {
      if(this.noAuthMenu.length === 0) {
        this.$message.error("无新菜单");
        return;
      }
      console.log(this.noAuthMenu);
      batchCreate(this.noAuthMenu).then(res => {
        this.$message.success("添加成功");
        this.$emit('data-change');
        this.$refs.detailDialog.hide();
      })
    },

    checkMenuAuth() {
      res = [];
      menuFilter(asyncRoutes);
      this.noAuthMenu = res;
    },

    getList() {
      list().then(res => {
        let menus = res.rows;
        menus.forEach(item => {
          if(item.menuUrl) {
            let path = '';
            let pageArr = item.menuUrl.match(/\/[^\/]+/g); //匹配 /xxx
            if(pageArr) {
              pageArr.forEach(page => {
                path += page;
                menuIndexObj[path] = item;
              })
            }
          }
        });
        this.checkMenuAuth();
      })
    }
  }
}
</script>

<style lang="scss">
  .dialog-body {

  }
</style>
